import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import "../../styles" as Styles

Rectangle {
    id: dataGrid

    // 自定义属性
    property var columnModel: []          // 列定义: [{key, title, width, sortable}]
    property var dataModel: []            // 数据模型
    property int selectedRow: -1          // 选中行索引
    property string sortColumn: ""        // 排序列
    property bool sortAscending: true     // 排序方向
    property bool multiSelect: false      // 是否支持多选
    property var selectedRows: []         // 多选时的选中行索引数组
    property bool showHeader: true        // 是否显示表头
    property bool alternatingRowColors: true  // 是否交替行颜色
    property bool enableSorting: true     // 是否启用排序

    // 默认样式
    color: Styles.Theme.surface
    border.color: Styles.Theme.border
    border.width: 1
    radius: Styles.Theme.radiusNormal

    // 信号
    signal rowClicked(int index, var rowData)
    signal rowDoubleClicked(int index, var rowData)
    signal selectionChanged(var selectedIndexes)
    signal sortRequested(string column, bool ascending)

    Column {
        anchors.fill: parent
        anchors.margins: 1

        // 表头
        Rectangle {
            visible: showHeader
            width: parent.width
            height: 40
            color: Styles.Theme.backgroundSecondary
            border.color: Styles.Theme.border
            border.width: 1

            Row {
                anchors.fill: parent

                Repeater {
                    model: columnModel

                    Rectangle {
                        width: modelData.width || (parent.width / columnModel.length)
                        height: parent.height
                        color: "transparent"
                        border.color: Styles.Theme.border
                        border.width: index < columnModel.length - 1 ? 1 : 0

                        Row {
                            anchors.centerIn: parent
                            spacing: Styles.Theme.spacingXSmall

                            Text {
                                text: modelData.title || modelData.key
                                color: Styles.Theme.textPrimary
                                font.pixelSize: Styles.Theme.fontSizeNormal
                                font.weight: Styles.Theme.fontWeightMedium
                                anchors.verticalCenter: parent.verticalCenter
                            }

                            // 排序指示器
                            Text {
                                visible: enableSorting && (modelData.sortable !== false) && sortColumn === modelData.key
                                text: sortAscending ? "▲" : "▼"
                                color: Styles.Theme.primary
                                font.pixelSize: 10
                                anchors.verticalCenter: parent.verticalCenter
                            }
                        }

                        // 表头点击处理
                        MouseArea {
                            anchors.fill: parent
                            cursorShape: (enableSorting && modelData.sortable !== false) ? Qt.PointingHandCursor : Qt.ArrowCursor

                            onClicked: {
                                if (enableSorting && modelData.sortable !== false) {
                                    if (sortColumn === modelData.key) {
                                        sortAscending = !sortAscending
                                    } else {
                                        sortColumn = modelData.key
                                        sortAscending = true
                                    }
                                    dataGrid.sortRequested(modelData.key, sortAscending)
                                }
                            }

                            Rectangle {
                                anchors.fill: parent
                                color: "white"
                                opacity: parent.containsMouse && enableSorting && (modelData.sortable !== false) ? 0.1 : 0
                                Behavior on opacity { NumberAnimation { duration: 150 } }
                            }
                        }
                    }
                }
            }
        }

        // 数据行
        ScrollView {
            width: parent.width
            height: parent.height - (showHeader ? 40 : 0)
            clip: true

            Column {
                width: parent.width

                Repeater {
                    model: dataModel

                    Rectangle {
                        width: parent.width
                        height: 40
                        color: {
                            if (selectedRows.indexOf(index) !== -1 || selectedRow === index) {
                                return Styles.Theme.primary
                            }
                            if (alternatingRowColors && index % 2 === 1) {
                                return Styles.Theme.backgroundSecondary
                            }
                            return "transparent"
                        }

                        border.color: Styles.Theme.border
                        border.width: index < dataModel.length - 1 ? 1 : 0

                        Row {
                            anchors.fill: parent

                            Repeater {
                                model: columnModel

                                Rectangle {
                                    width: modelData.width || (parent.width / columnModel.length)
                                    height: parent.height
                                    color: "transparent"
                                    border.color: Styles.Theme.border
                                    border.width: index < columnModel.length - 1 ? 1 : 0

                                    Text {
                                        anchors.left: parent.left
                                        anchors.leftMargin: Styles.Theme.spacingSmall
                                        anchors.verticalCenter: parent.verticalCenter
                                        text: getCellValue(modelData.key, parent.parent.parent.index)
                                        color: getCellColor(parent.parent.parent.index)
                                        font.pixelSize: Styles.Theme.fontSizeNormal
                                        elide: Text.ElideRight
                                        width: parent.width - Styles.Theme.spacingSmall * 2
                                    }
                                }
                            }
                        }

                        // 行点击处理
                        MouseArea {
                            anchors.fill: parent
                            onClicked: {
                                handleRowClick(index)
                                dataGrid.rowClicked(index, dataModel[index])
                            }

                            onDoubleClicked: {
                                dataGrid.rowDoubleClicked(index, dataModel[index])
                            }

                            Rectangle {
                                anchors.fill: parent
                                color: "white"
                                opacity: parent.containsMouse ? 0.1 : 0
                                Behavior on opacity { NumberAnimation { duration: 150 } }
                            }
                        }
                    }
                }
            }
        }
    }

    // 辅助函数
    function getCellValue(key, rowIndex) {
        if (rowIndex >= 0 && rowIndex < dataModel.length) {
            var rowData = dataModel[rowIndex]
            return rowData[key] || ""
        }
        return ""
    }

    function getCellColor(rowIndex) {
        if (selectedRows.indexOf(rowIndex) !== -1 || selectedRow === rowIndex) {
            return Styles.Theme.textOnPrimary
        }
        return Styles.Theme.textPrimary
    }

    function handleRowClick(index) {
        if (multiSelect) {
            var currentIndex = selectedRows.indexOf(index)
            var newSelection = selectedRows.slice() // 复制数组

            if (currentIndex !== -1) {
                // 取消选择
                newSelection.splice(currentIndex, 1)
            } else {
                // 添加选择
                newSelection.push(index)
            }

            selectedRows = newSelection
            selectionChanged(selectedRows)
        } else {
            selectedRow = (selectedRow === index) ? -1 : index
            selectedRows = selectedRow !== -1 ? [selectedRow] : []
            selectionChanged(selectedRows)
        }
    }

    // 公共方法
    function clearSelection() {
        selectedRow = -1
        selectedRows = []
        selectionChanged([])
    }

    function selectRow(index) {
        if (index >= 0 && index < dataModel.length) {
            if (multiSelect) {
                if (selectedRows.indexOf(index) === -1) {
                    selectedRows = selectedRows.concat([index])
                    selectionChanged(selectedRows)
                }
            } else {
                selectedRow = index
                selectedRows = [index]
                selectionChanged(selectedRows)
            }
        }
    }

    function selectAll() {
        if (multiSelect) {
            var allIndexes = []
            for (var i = 0; i < dataModel.length; i++) {
                allIndexes.push(i)
            }
            selectedRows = allIndexes
            selectionChanged(selectedRows)
        }
    }
}